﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppPlanProduccion.ServiceReference.AuthApi;
using WebAppPlanProduccion.Code;
using System.Configuration;
using Web.Framework.Config;

namespace WebAppPlanProduccion.Account
{
    public partial class Login : BasePage
    {       
        protected void Page_Load(object sender, EventArgs e)
        {           
            masterPage.MakeMenuVisible(false);
            //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            LoginUser.Authenticate += new AuthenticateEventHandler(LoginUser_Authenticate);

            ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

            BaseMasterPage.ApplicationId = configuration.ApplicationId;

            var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
            ctrl.DataSource = WebServiceHelper.GetCompanies(BaseMasterPage.ApplicationId);
            ctrl.DataValueField = "Id";
            ctrl.DataTextField = "Name";
            ctrl.DataBind();
        }

        void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {           
            var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
            ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

            if (LoginUser.UserName == configuration.SuperAdminName && LoginUser.Password == configuration.SuperAdminPassword)
            {
                e.Authenticated = true;
                BaseMasterPage.CompanyId = Convert.ToInt32(ctrl.SelectedValue);
                BaseMasterPage.UserName = LoginUser.UserName;
                BaseMasterPage.IsAdmin = true;
            }
            else if (e.Authenticated = WebServiceHelper.Authenticate(BaseMasterPage.ApplicationId, Convert.ToInt32(ctrl.SelectedValue), LoginUser.UserName, LoginUser.Password))
            {
                BaseMasterPage.CompanyId = Convert.ToInt32(ctrl.SelectedValue);
                BaseMasterPage.UserName = LoginUser.UserName;
                BaseMasterPage.IsAdmin = false;
            }
        }
    }
}
